package mango.server;
 

import java.io.*;
import java.net.*;


public class Connection extends Thread {
	static int connectionID = 0;
	protected Socket client;
	protected Vulture vulture;
	protected DataInputStream in;
	protected PrintStream out;
	protected Protocol proto;
	protected MangoServer parent;
	
	public Connection (Socket c, ThreadGroup threads, int priority, Vulture v, MangoServer p) {
		super(threads, "Connection:"+connectionID);
		this.setPriority(priority);
		connectionID++;
		
		vulture = v;
		client = c;
		
		try {
			in = new DataInputStream(client.getInputStream());
			out = new PrintStream(client.getOutputStream());
		}
		catch (IOException e) {
			try {client.close();} catch (IOException e2) {}
			System.err.println("<!> Exception while getting socket streams: " + e);			
			return;
		}
		
		proto = new Protocol(this);
		
		this.start();
	}
	
	public void run() {
		out.println("    +-----------------------------------+");
		out.println("    | Logged in to Pokemon Mango Server |");
		out.println("    |                                   |");
		out.println("<#> |                                   |");
		out.println("    | (c) Daniels, Engle, Mills, Seay,  |");
		out.println("    |     Taperman, Walle, and Zhu.     |");
		out.println("    +-----------------------------------+");
		
		try {
			for (;;) {
				String line = in.readLine();
				if (line==null) { 
					break;
				}
				else {
					try {
						String[] parts;
						if (line.indexOf("|")>=0) {
							parts = line.split("[|]");
							String[] args;
							if (parts[1].indexOf(",") >= 0) {
								args = parts[1].split("[,]");
							}
							else {
								args = new String[1];
								args[0] = parts[1];
							}
							proto.execute(parts[0], args);
						}
						else {
							pushToClient("<!> Command does not follow format 'command' (pipe) 'args'");
						}
					} catch (NullPointerException e) {
						pushToClient("<!> Command does not follow format 'command' (pipe) 'args :"+e);
					}
				}
			}
		} catch (IOException e) {}
		finally {
			try {client.close();} catch (IOException e2) {}
			synchronized (vulture) {vulture.notify();}
		}
	}
	public void pushToClient (String st) {
	    out.println(st);
	}
	public String toString() {
		return this.getName() + " connected to: "
		+ client.getInetAddress().getHostName() 
		+ ":" + client.getPort();
	}
	public void shutdown() {}
}
